'''

Case Type： 控制文件
Case Name： 控制文件清空
Create At:  2020/07/01
Owner    :  @wan005
Descption:  1.控制文件和备份文件都清空，数据库运行时checkpoint，启动数据库、停止数据库 2.只清空控制文件，不清空备份控制文件

'''
import os
import sys
import unittest
import _thread
import time
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common


class ClearCtrl(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case072.py start------------')
        self.DN1_PATH = macro.DB_INSTANCE_PATH
        self.PG_CONTROL_PATH = macro.PG_CONTROL_PATH
        self.dbUserNode = Node(node='dbuser')
        self.rootNode = Node()
        self.com = Common()
        self.Constant = Constant()

        # 进行备份操作
        cmd = f'cp -r {self.PG_CONTROL_PATH}* {macro.DB_BACKUP_PATH}'
        self.log.info(cmd)
        msg = self.dbUserNode.sh(cmd).result()

    def test_clear_allctrl(self):
        # 清空控制文件及备份文件
        cmd = f'> {self.PG_CONTROL_PATH}'
        self.log.info(cmd)
        msg = self.dbUserNode.sh(cmd).result()
        cmd = f'> {self.PG_CONTROL_PATH}.backup'
        self.log.info(cmd)
        msg = self.dbUserNode.sh(cmd).result()

        # 数据库运行时checkpoint
        cmd = "checkpoint;"
        msg = self.sh.executDbSql(cmd)
        self.log.info(cmd)
        is_checkpoint = msg.find('CHECKPOINT') > -1
        self.assertTrue(is_checkpoint)

        # 停止数据库成功
        is_stop = self.sh.stopDbCluster()
        self.assertTrue(is_stop)

        time.sleep(2)

        # 启动数据库成功
        is_started = self.sh.startDbCluster()
        self.assertTrue(is_started)

    def test_clear_ctrlbak(self):
        # 只清空控制文件不修改备份文件
        cmd = f'> {self.PG_CONTROL_PATH}'
        self.log.info(cmd)
        msg = self.dbUserNode.sh(cmd).result()

        # 数据库运行时checkpoint
        cmd = "checkpoint;"
        msg = self.sh.executDbSql(cmd)
        self.log.info(cmd)
        is_checkpoint = msg.find('CHECKPOINT') > -1
        self.assertTrue(is_checkpoint)

        # 停止数据库
        is_stop = self.sh.stopDbCluster()
        self.assertTrue(is_stop)

        time.sleep(2)

        # 启动数据库
        is_started = self.sh.startDbCluster()
        self.assertTrue(is_started)

    def tearDown(self):
        self.log.info("----------------------------------this is tearDown-----------------------")
        backup_path = os.path.basename(self.PG_CONTROL_PATH) + '*'
        (global_path, tempfilename) = os.path.split(self.PG_CONTROL_PATH)
        cmd = f'mv  {os.path.join(macro.DB_BACKUP_PATH, backup_path)} {global_path}'
        self.log.info(cmd)
        msg = self.dbUserNode.sh(cmd).result()
        self.log.info(msg)
